const date = new Date();
const years = [];
const months = [];
const days = [];

for (let i = 2010; i <= date.getFullYear(); i++) {
  years.push(i);
}

for (let i = 1; i <= 12; i++) {
  months.push(i);
}

for (let i = 1; i <= 31; i++) {
  days.push(i);
}

//字符串截取

var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    images_arr: [],
    wrapCategoryOne: false,
    wrapCategoryTwo: false,
    animationData: {},
    category: '', //标识二级类目对应一级类目
    categoryStatusOne: false,
    categoryStatusTwo: false,
    categoryTextOne: '请选择类型',
    categoryTextTwo: '请选择科目',
    listCategoryOne: [{ id: 1, name: '收入' }, { id: 2, name: '支出' }], //存放类型
    categorySelectOne: '', //判断是否选中

    textOne: '', //用于存储回收类别列表值得变量
    categoryIdOne: '',
    idOne: '', //类别id
    listCategoryTwo: '', //存放科目
    categorySelectTwo: '',
    textTwo: '',
    idTwo: '',
    categoryIdTwo: '',
    bookPrice: '', //单价
    wrapDate: false,
    dataStatus: false,
    years: years,
    year: date.getFullYear(),
    months: months,
    month: date.getMonth() + 1,
    days: days,
    day: date.getDate(),
    value: [9999, date.getMonth(), date.getDate() - 1],
    sendDate: '',
    sendName: '', //经手人
    describe: '' //说明
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
  },
  bindSendName(e) {
    this.setData({ sendName: e.detail.value });
  },
  bindDescribe(e) {
    this.setData({ describe: e.detail.value });
  },
  //显示一级品类弹窗事件
  wrapCategorySelectOne: function(e) {
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 200,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    });
    // 将该变量赋值给当前动画
    that.animation = animation;
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step();
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      wrapCategoryOne: true
    });
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function() {
      animation.translateY(0).step();
      that.setData({
        animationData: animation.export()
      });
    }, 200);
  },
  //隐藏弹窗事件
  hideModal: function(e) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'linear'
    });
    that.animation = animation;
    animation.translateY(200).step();
    that.setData({
      animationData: animation.export()
    });
    setTimeout(function() {
      animation.translateY(0).step();
      that.setData({
        animationData: animation.export(),
        wrapCategoryOne: false,
        wrapCategoryTwo: false,
        wrapDate: false
      });
    }, 200);
  },
  //一级类目底部弹层选择事件
  categoryListOne: function(e) {
    console.log(e.currentTarget.dataset.select);
    var that = this;
    that.setData({
      //把选中值放入判断值
      categorySelectOne: e.currentTarget.dataset.select,
      textOne: e.currentTarget.dataset.text,
      idOne: e.currentTarget.dataset.id
    });
  },

  //一级品类确定事件
  sureBtnOne: function() {
    var that = this;
    if (that.data.textOne) {
      that.setData({
        categoryStatusOne: true,
        categoryTextOne: that.data.textOne,
        categoryIdOne: that.data.idOne
      });
    }
    that.hideModal();
    console.log(that.data.category + ',' + that.data.categoryTextOne);
    console.log(that.data.categoryTextOne);
    if (that.data.category != that.data.categoryTextOne) {
      console.log('不同');
      that.setData({
        categoryStatusTwo: false,
        categoryTextTwo: '请选择科目',
        categorySelectTwo: '',
        textTwo: '',
        idTwo: ''
      });
    }
    this.setData({ category: that.data.textOne });
  },

  //显示二级品类弹窗事件
  wrapCategorySelectTwo: function(e) {
    var that = this;
    if (that.data.categorySelectOne == '') {
      wx.showToast({ title: '请先选择类型', icon: 'none' });
      return;
    }
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear'
    });
    that.animation = animation;
    animation.translateY(200).step();
    that.setData({
      animationData: animation.export(),
      wrapCategoryTwo: true
    });
    setTimeout(function() {
      animation.translateY(0).step();
      that.setData({
        animationData: animation.export()
      });
    }, 200);

    if (that.data.categorySelectOne == 1) {
      that.setData({
        listCategoryTwo: [
          { id: 1, name: '销货收入' },
          { id: 2, name: '杂料收入' },
          { id: 3, name: '租金收入' },
          { id: 4, name: '其他收入' }
        ]
      });
    } else if (that.data.categorySelectOne == 2) {
      that.setData({
        listCategoryTwo: [
          { id: 5, name: '购货支出' },
          { id: 6, name: '工资支出' },
          { id: 7, name: '运输支出' },
          { id: 8, name: '租金水电' },
          { id: 9, name: '设备及维修' },
          { id: 10, name: '其他支出' }
        ]
      });
    }
  },

  //二级类目底部弹层选择事件
  categoryListTwo: function(e) {
    console.log(e);
    var that = this;
    that.setData({
      //把选中值放入判断值
      categorySelectTwo: e.currentTarget.dataset.select,
      textTwo: e.currentTarget.dataset.text,
      idTwo: e.currentTarget.dataset.id
    });
  },

  //二级品类确定事件
  sureBtnTwo: function() {
    var that = this;
    if (that.data.textTwo) {
      that.setData({
        categoryStatusTwo: true,
        categoryTextTwo: that.data.textTwo,
        categoryIdTwo: that.data.idTwo
      });
    }
    that.hideModal();
  },

  //日期展示
  wrapDateSelect: function() {
    var that = this;
    var animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'linear'
    });
    that.animation = animation;
    animation.translateY(200).step();
    that.setData({
      ifscroll: true,
      animationData: animation.export(),
      wrapDate: !that.data.wrapDate
    });
    setTimeout(function() {
      animation.translateY(0).step();
      that.setData({
        animationData: animation.export()
      });
    }, 0);
  },
  //日期类别选择
  bindChange: function(e) {
    var that = this;
    var val = e.detail.value;
    that.setData({
      year: that.data.years[val[0]],
      month: that.data.months[val[1]],
      day: that.data.days[val[2]]
      // value: [9999, that.data.months[val[1]] - 1, that.data.days[val[2]]-1],
    });
  },

  //日期确定事件
  sureDateBtn: function() {
    var that = this;
    that.setData({
      dataStatus: true,
      date:
        that.data.year + '年' + that.data.month + '月' + that.data.day + '日',
      sendDate: that.data.year + '-' + that.data.month + '-' + that.data.day
    });
    that.hideModal();
  },
  upload: function(item) {
    var that = this;
    wx.showLoading({
      title: '上传中'
    });
    wx.uploadFile({
      url: app.preUrl + 'uploadFile',
      header: {
        'Content-Type': 'multipart/form-data'
      },
      filePath: item,
      name: 'file',
      formData: {
        userId: app.globalData.userId //附加信息为用户ID
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        var imgUrl =
          'https://www.lvdaxia.com.cn/dabaozhan/fileImage/' +
          JSON.parse(res.data).result;
        that.setData({
          images_arr: that.data.images_arr.concat(imgUrl)
        });
      }
    });
  },
  upimg: function() {
    let that = this;
    let len = 0;
    len = 3 - this.data.images_arr.length;
    if (len == 0) {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'loading',
        duration: 1500
      });
      return;
    }
    wx.chooseImage({
      count: len,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(res);
        tempFilePaths.forEach(function(item, index) {
          that.upload(item);
        });
      }
    });
  },

  // 删除图片
  deleteImg: function(e) {
    var that = this;
    var images = that.data.images_arr;
    var index = e.currentTarget.dataset.index;
    images.splice(index, 1);
    that.setData({
      images_arr: images
    });
  },

  //录入单价
  onNumberPrice: function(e) {
    var that = this;
    that.setData({ bookPrice: e.detail.value.replace(/[^\d.]/g, '') });
    that.setData({ bookPrice: e.detail.value.replace(/\.{2,}/g, '.') });
    that.setData({
      bookPrice: e.detail.value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    });
    that.setData({
      bookPrice: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    });
  },

  bindFormSubmit: function() {
    var that = this;
    if (!that.data.categoryStatusOne) {
      wx.showToast({ title: '请选择类型', icon: 'none' });
      return false;
    }
    if (!that.data.categoryStatusTwo) {
      wx.showToast({ title: '请选择科目', icon: 'none' });
      return false;
    }
    if (!that.data.bookPrice) {
      wx.showToast({ title: '请输入金额', icon: 'none' });
      return false;
    }
    if (!that.data.sendDate) {
      wx.showToast({ title: '请选择时间', icon: 'none' });
      return false;
    }
    if (!that.data.sendDate) {
      wx.showToast({ title: '请选择时间', icon: 'none' });
      return false;
    }
    if (!that.data.sendName) {
      wx.showToast({ title: '填写经手人', icon: 'none' });
      return false;
    }
    if (!that.data.describe) {
      wx.showToast({ title: '填写说明', icon: 'none' });
      return false;
    }

    wx.showLoading({
      title: '提交中'
    });
    that.setData({
      buthidden: true
    });
    wx.request({
      method: 'POST',
      url: app.preUrl + 'addBill',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: app.globalData.userId, //
        bookType: that.data.categoryIdOne, //记账类型 1:收入 2：支付
        bookSubject: that.data.categoryIdTwo, //记账科目 1:销货收入 2:杂料收入 3:租金收入 4:其他收入 5:购货支出 6:工资支出 7:运输支出 8:租金水电 9:设备及维修 10:其他支出
        bookPrice: that.data.bookPrice,
        bookName: that.data.sendName,
        bookDetail: that.data.describe,
        pictureList: that.data.images_arr,
        tradeTime: that.data.sendDate
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.code == 100) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 1000
          });
          setTimeout(function() {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            confirmColor: '#56BDE0',
            showCancel: false
          });
          that.setData({ buthidden: false });
        }
      },
      fail: function(error) {
        that.setData({
          buthidden: false
        });
      }
    });
  }
});
